package uns.fit.gis.ui;

import java.util.Vector;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;

import mobiletrailexplorer.osm.OpenStreetMapUploadForm;

import uns.fit.gis.MapDrawer;
import uns.fit.gis.Util;
import uns.fit.gis.fileio.FileWrapper;
import uns.fit.gis.i18n.LocaleManager;
import uns.fit.gis.mapdrawer.MapCanvas;
import uns.fit.gis.rms.RSManager;

public class RouteList extends List implements CommandListener {
	private Command backCommand;
	private Command selectCommand;
	private Command deleteCommand;
	private Command deleteYesCommand;
	private Command deleteNoCommand;
	private Command convertToKmlCommand;
	private MapDrawer midlet;
	private static Font font;
	
	public RouteList(MapDrawer midlet) {
		super("", List.IMPLICIT);
		this.midlet = midlet;
		backCommand = new Command(LocaleManager.getMessage("back"), Command.BACK, 1);
		addCommand(backCommand);
		selectCommand = new Command(LocaleManager.getMessage("showmap"), Command.ITEM, 1);
		addCommand(selectCommand);
		convertToKmlCommand = new Command("KML", Command.ITEM, 1);
		addCommand(convertToKmlCommand);
		deleteCommand = new Command(LocaleManager.getMessage("deletetracklog"), Command.ITEM, 1);
		addCommand(deleteCommand);
		deleteYesCommand = new Command(LocaleManager.getMessage("yes"), Command.OK, 1);
		deleteNoCommand = new Command(LocaleManager.getMessage("no"), Command.CANCEL, 1);
		setCommandListener(this);
		appendAllTracks();
		font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
	}
	
	private void appendAllTracks() {
		RSManager.open(Util.GPS_TRACK_RECORDSTORE_NAME);
		Vector names = RSManager.loadAllTrackNames();
		for(int i = 0; i < names.size(); i ++) {
			String str = (String)names.elementAt(i);
			append(str, null);
		}
		RSManager.close();
	}

	public RouteList(String title, int listType) {
		super(title, listType);
		// TODO Auto-generated constructor stub
	}

	public RouteList(String title, int listType, String[] stringElements,
			Image[] imageElements) {
		super(title, listType, stringElements, imageElements);
		// TODO Auto-generated constructor stub
	}

	public void commandAction(Command command, Displayable displayable) {
		if(command == backCommand) {
			midlet.showMapCanvas();
		}
		else if(command == selectCommand) {
			if(getSelectedIndex() != -1) {
				getTrack(getId(getString(getSelectedIndex())));
				int point = ((Integer)MapCanvas.track.elementAt(0)).intValue();
				Util.centerScreen((point >> 16) & 0xFFFF, point & 0xFFFF);
				midlet.showMapCanvas();
			}
		}
		else if(command == convertToKmlCommand) {
			if(getSelectedIndex() != -1) {
				getTrack(getId(getString(getSelectedIndex())));
				final String kml = convertToKml(getString(getSelectedIndex()), MapCanvas.track);
				
				new Thread() {
					public void run() {
						FileWrapper.save(kml.getBytes(), midlet.getSettings().getStorageFolder() + getString(getSelectedIndex()).replace(' ', '_').replace(':', '_') + ".kml");
					}
				}.start();
				
				midlet.show(new OpenStreetMapUploadForm(MapCanvas.track));
			}
		}
		else if(command == deleteCommand) {
			Alert alert = new Alert("", LocaleManager.getMessage("deleteconfirm"), null, AlertType.CONFIRMATION );
			//alert.setTimeout(Alert.FOREVER);
			alert.addCommand(deleteYesCommand);
			alert.addCommand(deleteNoCommand);
			alert.setCommandListener(this);
			MapDrawer.showAlert(alert, this);
		}
		else if(command == deleteYesCommand) {
			System.out.println("Deleted");
			midlet.showRouteList();
			RSManager.open(Util.GPS_TRACK_RECORDSTORE_NAME);
			RSManager.deleteTrack(getId(getString(getSelectedIndex())));
			RSManager.close();
		}
		else if(command == deleteNoCommand) {
			System.out.println("Cancel");
			midlet.showRouteList();
			// Nothing to do
		}
	}

	private String convertToKml(String name, Vector track) {
		StringBuffer trackString = new StringBuffer();

        addHeader(trackString, name);

        int point = 0;
        for(int i = 0; i < track.size(); i ++) {
        	point = ((Integer)track.elementAt(i)).intValue();
            trackString.append(Util.getLongitude((point >> 16) & 0xFFFF)).append(",")
                    .append(Util.getLatitude((short)(point & 0xFFFF))).append("\r\n");
        }
        closeTrack(trackString);
        addFooter(trackString);
        return trackString.toString();
	}
	
	public static void addHeader(StringBuffer trackString, String dateStamp) {
        trackString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
        trackString
                .append("<kml xmlns=\"http://earth.google.com/kml/2.0\">\r\n");

        trackString.append("<Folder>\r\n");
        trackString.append("<name>").append(dateStamp).append("</name>\r\n");
        trackString.append("<Style id=\"style\">\r\n");
        trackString.append(" <LineStyle>\r\n");
        trackString.append("  <color>ff0000ff</color>\r\n");
        trackString.append("  <width>1.5</width>\r\n");
        trackString.append(" </LineStyle>\r\n");
        trackString.append(" <PolyStyle>\r\n");
        trackString.append("  <fill>0</fill>\r\n");
        trackString.append(" </PolyStyle>\r\n");
        trackString.append("</Style>\r\n");
        trackString.append("<open>1</open>\r\n");
        trackString.append("<Placemark>\r\n");
        trackString.append("<styleUrl>#style</styleUrl>\r\n");
        trackString.append("<LineString>\r\n");
        trackString.append("<extrude>0</extrude>\r\n");
        trackString.append("<altitudeMode>clampToGround</altitudeMode>\r\n");
        trackString.append("<coordinates>\r\n");
    }
	
	public static void closeTrack(StringBuffer trackString) {
        trackString.append("</coordinates>\r\n");
        trackString.append("</LineString>\r\n");
        trackString.append("</Placemark>\r\n");
    }

    public static void addFooter(StringBuffer trackString) {
        trackString.append("</Folder>\r\n");
        trackString.append("</kml>\r\n");
    }
    
	private void getTrack(int id) {
		RSManager.open(Util.GPS_TRACK_RECORDSTORE_NAME);
		MapCanvas.track = RSManager.loadTrack(id);
		MapCanvas.drawTrack = true;
		RSManager.close();
	}
	
	private int getId(String name) {
		return Integer.valueOf(Util.split(name, ".")[0]).intValue();
	}
}
